package orders

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"
	"strings"

	"insighttracking/apps/customer/internal/svc"
	"insighttracking/apps/customer/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersPageApiLogic) GetOrdersPageApi(req *types.GetOrdersPageReq) (resp *types.GetOrdersPageResp, err error) {
	// todo: add your logic here and delete this line
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	customerId := cast.ToInt64(l.ctx.Value("customerId"))
	tx := dao.OrdersEntity.WithContext(l.ctx).Where(
		dao.OrdersEntity.EnterpriseID.Eq(enterpriseId),
		dao.OrdersEntity.CustomerID.Eq(customerId),
	)
	if req.OrderNo != "" {
		tx = tx.Where(dao.OrdersEntity.OrderNo.Eq(req.OrderNo))
	}
	// 待采购/已采购/已入库/已发货/已收货
	if req.Status != "" {
		tx = tx.Where(dao.OrdersEntity.Status.Eq(cast.ToInt64(req.Status)))
	}
	if req.StartDate != "" && req.EndDate != "" {
		tx = tx.Where(dao.OrdersEntity.CreatedAt.Between(utils.DateTimeStrToTime(req.StartDate), utils.DateTimeStrToTime(req.EndDate)))
	}
	if req.Name != "" {
		req.Name = strings.ReplaceAll(req.Name, "%", "\\%")
		req.Name = strings.ReplaceAll(req.Name, "_", "\\%")
		orderDetailList, err := dao.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.SnapshotName.Like("%" + req.Name + "%")).Find()
		fmt.Println("-------??-----")
		if err == nil && len(orderDetailList) > 0 {
			orderIdList := k.Map(orderDetailList, func(item *model.OrdersDetailEntity, index int) int64 {
				return item.OrdersID
			})
			tx = tx.Where(dao.OrdersEntity.ID.In(orderIdList...))
		} else {
			return &types.GetOrdersPageResp{
				Data: make([]types.GetOrdersResp, 0),
				PageBaseResp: types.PageBaseResp{
					Total:      0,
					PageSize:   req.PageSize,
					PageNumber: req.PageNumber,
				},
			}, nil
		}
	}
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	ordersEntities, count, err := tx.Order(dao.OrdersEntity.ID.Desc()).FindByPage(offset, limit)
	var ordersResp = make([]types.GetOrdersResp, 0)
	for _, item := range ordersEntities {
		ordersResp = append(ordersResp, types.GetOrdersResp{
			ID:               item.ID,                                                                           // 主键id
			OrderNo:          item.OrderNo,                                                                      // 订单流水号
			SendGoodsDate:    k.If(item.SendGoodsDate.IsZero(), 0, utils.TimestampToString(item.SendGoodsDate)), // 发货日期
			SendGoodsMethod:  item.SendGoodsMethod,                                                              // 发货方式,0表示司机配送
			SettlementMethod: item.SettlementMethod,                                                             // 结算方式，0表示账期
			PurchaserID:      item.PurchaserID,                                                                  // 采购员,关联到
			//PurchaserName:      item.PurchaserName,      // 采购员,关联到
			Remark:             item.Remark,                             // 订单备注
			TotalAmount:        item.TotalAmount.StringFixed(2),         // 订单金额
			TotalCount:         item.TotalCount.StringFixed(2),          // 订单商品数量
			Status:             item.Status,                             // 订单状态,0表示已下单(待采购),1表示采购中,2表示已采购,3待入库，4已入库，5已发货,6已收货
			ReceiveGoodsName:   item.ReceiveGoodsName,                   // 收货员姓名
			ReceiveGoodsMobile: item.ReceiveGoodsMobile,                 // 收货人手机号码
			ReceiveAddress:     item.ReceiveAddress,                     // 收货人地址
			IsPurchasingPlan:   item.IsPurchasingPlan,                   // 是否发布采购计划,0表示不发布,1表示发布
			CreatedAt:          utils.TimestampToString(item.CreatedAt), // 创建时间
			UpdatedAt:          utils.TimestampToString(item.UpdatedAt), // 更新时间
		})
	}
	if err != nil {
		return &types.GetOrdersPageResp{
			Data: make([]types.GetOrdersResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	return &types.GetOrdersPageResp{
		Data: ordersResp,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
